import React from "react"
// import "../Song"
import RightList from "./right"
import "../../assets/styles/song.css"
import {Link,BrowserRouter,Route,Switch} from "react-router-dom";
import ReactDOM from "react-dom"
import SongList from "../SongList"
import Audio from "react-audio-player"
import {observer,inject} from "mobx-react";
import songStore from "../../store/SongStore"
import { ActionSheet, WingBlank, WhiteSpace, Button, Toast } from 'antd-mobile';
import {parseLyric,formatTime} from './Format';
// import x from "./Audio"

// import songstore from "../../store/SongStore"
@inject("songStore") 
@observer
// const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
// let wrapProps;
// if (isIPhone) {
//   wrapProps = {
//     onTouchStart: e => e.preventDefault(),
//   };
// }

class Song extends React.Component{
    
    constructor(props){
        super(props)
        this.state={
            isPlay:false,
            id:"65538",
            clicked: 'none',
            clicked1: 'none',
            clicked2: 'none',
            pValue:0,
			currentId:-1,
			isShowlist:false,
        	isShow:false,
        	isLove:false,
            song: [],
            lyrics:[],
            songList: global.songList,
            latelyList:[],
            collectList:[],
        }
        // this.x=document.getElementById("myAudio")
        // this.collectTap = this.collectTap.bind(this);
        // this.hiddenSongList = this.hiddenSongList.bind(this);
        // this.showSongList = this.showSongList.bind(this);
        
        // this.progressChange = this.progressChange.bind(this);
    }
    dataList = [
        { url: 'OpHiXAcYzmPQHcdlLFrc', title: '发送给朋友' },
        { url: 'wvEzCMiDZjthhAOcwTOu', title: '新浪微博' },
        { url: 'cTTayShKtEIdQVEMuiWt', title: '生活圈' },
        { url: 'umnHwvEgSyQtXlZjNJTt', title: '微信好友' },
        { url: 'SxpunpETIwdxNjcJamwB', title: 'QQ' },
      ].map(obj => ({
        icon: <img src={`https://gw.alipayobjects.com/zos/rmsportal/${obj.url}.png`} alt={obj.title} style={{ width: 36 }} />,
        title: obj.title,
      }));
      componentWillUnmount(){    //解决切换路由时，setState被卸载问题
        this.setState = (state,callback)=>{ //重写组件的setState方法，直接返回空
          return;
        };  
        }
      componentDidMount(){
	    // if(global.hash){
        const {songStore} =this.props;
        songStore.getSongInfomationList("1376832321");
        console.log(songStore.songs)
        songStore.getSonglyrics("1376832321");
        console.log(songStore.lyrics)
        songStore.getSonglistlist("2751980925");
        console.log(songStore.songlistlist);
        
        // this.GetMusic(global.hash);
        // window.
        this.setState({
            song:"https://v1.itooi.cn/netease/url?id=65538&quality=320"
        })
        var x = document.getElementById("myAudio");
            console.log(x);
            if(this.state.song){
                this.playtimer = setInterval(() => {
                    this.timeUpdate();
                //     this.setState({currentHash:global.hash});
                //     // if(x.currentTime == x.duration){
                //     //     this.EndChangeSong();
                //     //  }
                }, 500  );
                this.changeCollectShow();
                var _this = this
                // x.play();
                
                // var timer = setTimeout(() => {x.play();_this.latelyList();}, 500);
            }else{
                	x.pause()
                	this.setState({
                		isShow:true,
                		isPlay:true
                	})
                }	
	    	
	    // }   	
        }
        // 歌词面板事件
        lyrScroll() {
        var x = document.getElementById("myAudio");             
            let lyrArry = []
            this.state.lyrics.map(function (lyr,i) {lyrArry.push(lyr[0])})
            for (var j = 0; j <= lyrArry.length; j++) {
                if (x.currentTime > lyrArry[j]) {this.setState({ currentId: j})}
            }
        }
        //判断是否收藏
        changeCollectShow() {
        var x = document.getElementById("myAudio");             
            if (global.collectList) {
              for (var i = 0; i < global.collectList.length; i++) {
                if (global.hash == global.collectList[i].hash) {
                   return this.setState({ isLove: true });
                }
              }
              return this.setState({ isLove: false });
            } else {
              this.setState({ isLove: false });
            }
        }
        //播放完自动随机切歌
        EndChangeSong (){
        var x = document.getElementById("myAudio");             
            
            let len = global.songList.length;
            let k =  Math.floor(Math.random() * len);
            global.hash = global.songList[k].hash;
            this.GetMusic(global.hash);
            this.changeCollectShow();
            let timer = setTimeout(()=> {x.play();}, 500);
        }
    
      showActionSheet = () => {
        var x = document.getElementById("myAudio");             
        const BUTTONS = ['Operation1', 'Operation2', 'Operation2', 'Delete', 'Cancel'];
        const  {songlistlist}=this.props.songStore;
        console.log(songlistlist);
        // BUTTONS=songlistlist
        ActionSheet.showActionSheetWithOptions({
          options: BUTTONS,
          cancelButtonIndex: BUTTONS.length - 1,
          destructiveButtonIndex: BUTTONS.length - 2,
          // title: 'title',
          message: '音乐列表',
          maskClosable: true,
          'data-seed': 'logId',
        //   wrapProps,
        },
        (buttonIndex) => {
          this.setState({ clicked: BUTTONS[buttonIndex] });
        });
      }
      //进度
      progressChange (e) {
        var x = document.getElementById("myAudio");         
		const pValue =  parseFloat(e.target.value)
		const seek = pValue * (x.duration/100);
        x.currentTime=seek;
		this.setState({pValue:pValue})
	    }
        // 音频进度改变触发事件
        timeUpdate(){
            var x = document.getElementById("myAudio"); 
            let pValue = x.currentTime / (x.duration/100);
            this.setState({pValue:pValue})
            this.lyrScroll()
        }
        //添加最近听过的歌
        latelyList () {
            let latelyList = this.state.latelyList;
            let GlobalLatelyList = global.latelyList
            if(GlobalLatelyList){
                for (var i = 0; i < 20; i++) {
                    // if (global.hash != global.latelyList[i].hash) {return global.latelyList.unshift(song);}else{return ;}
                }
            } else {
                // latelyList.push(song);
                global.latelyList = latelyList;
            }
        }
          //播放暂停
    playToggle(){
        var x = document.getElementById("myAudio"); 
        // this.x.play();
        console.log("hgjhg");
        // if(this.state.song){
            // this.setState({
            //     isPlay:false
            // })
            console.log(x.duration);
            
			if(this.state.isPlay){
				x.play()
				this.playtimer = setInterval(() => { this.timeUpdate()}, 500  );
			}else{
				x.pause()
				clearInterval(this.playtimer)
			}
		    this.setState({
				isPlay:!this.state.isPlay
			})

        }
        
    //上一首
    playPrev(){
        var x = document.getElementById("myAudio"); 
        const hash = global.hash;
        const songList = global.songList;
        let index = 0;
        if (songList.length > 0) {for (let i = 0; i < songList.length; i++) {if (songList[i].hash === hash) {index = i;}}}
        let currentIndex = index - 1 < 0 ? songList.length - 1 : --index;
        const currentSong = songList[currentIndex];
        global.hash = currentSong.hash
        this.GetMusic(currentSong.hash);
        this.changeCollectShow();
        this.setState({pValue:0,currentId:-1})
        if(this.state.isPlay){var timer = setTimeout(() => {x.play();}, 500);}
    }
  
    //下一首
    playNext(){
        var x = document.getElementById("myAudio");         
        console.log(66756);
        const hash = global.hash;
        const songList = global.songList;
        let index = 0;
        if (songList.length > 0) {for (let i = 0; i < songList.length; i++) { if (songList[i].hash === hash) {index = i;}}}
        let currentIndex = index - 1 < 0 ? songList.length - 1 : --index;
        const currentSong = songList[currentIndex];
        global.hash = currentSong.hash
        this.GetMusic(currentSong.hash);
        this.changeCollectShow();
        this.setState({pValue:0,currentId:-1})
        if(!this.state.isPlay){var timer = setTimeout(() => {x.play();}, 500);}
    }
    // handldianji(props){
    //       history.push({pathname: '/newSong'});

    // }
    render(){
        var x = document.getElementById("myAudio"); 
        // console.log(x.currentTime);
        // console.log(x);
        // let duration = formatTime(x.duration);
        var that = this;
        const  {songs}=this.props.songStore;
        const  {lyrics} =this.props.songStore;
        const  {songlistlist}=this.props.songStore;
        // console.log(songlistlist.tracks);
        let music=songs.songs;
        // console.log(music);
        
        
        return (
           
           <div className="back">
               {
                (music|| []).map(({name,ar,alia,al},index)=>{
                    var bg={
                        backgroundImage:'url('+ al.picUrl +')'
                    }   
                        return (
                            <div className="back-you">
                            <div className="songTop">
                            <span className="bottomTou"></span>
                            <span>{name}</span>
                            <span className="cebianlan"></span>
                        </div>
                        <div className="songAlbum">
                            <span>--</span>
                            <span>{ar[0].name}</span>
                            <span>{ar[1].name}</span>
                            <span>--</span>
                        </div>
                        <div className="songMusicX">
                            <div>HQ<i className="hqJiantou"></i></div>
                            <div>音效<span className="songXoff">off</span></div>
                        </div>
                        <div className="album">
                            <div className="albumImg" style={bg}></div>
                        </div>
                        <div className="songTitle">
                            <span>{name}</span>
                            <span>-</span>
                            <span>{ar[0].name},</span>
                            <span>{ar[1].name}</span>
                        </div>
                            {/* // 进度条 */}
                        {/* // <audio 
                        //     src="../../assets/test/我属于我自己-郑云龙 阿云嘎 声入人心第10期.mp3" 
                        //     ref="audio"  
                        //     // preload="metadata" 
                        //     controls
                        //     // autoPlay
                        //     id="audios"
                        //     muted
                        // >
                        // </audio> */}
                        <audio id="myAudio" autoPlay="autoPlay"> 
                            <source  src="https://v1.itooi.cn/netease/url?id=1376832321&quality=128"></source>
                        </audio>
                        <div className="progressT">
                            {/* <div className='time-box'> */}
                                {/* <span>{formatTime(x.currentTime)}</span> */}
                                {/* </div> */}
                            <div className='progress-bar'>
                                <span className="progress-change" style={{width: this.state.pValue + '%'}}></span>
                                {/* {console.log(this.state.pValue)} */}
                                <input type='range' step='0.01' max={100} min={0} value={this.state.pValue || '0'}  onChange={this.progressChange.bind(this)} className="progress-range"/>
                            </div>
                            {/* <span>{x.duration}</span> */}
                        </div>
                        {/* // <a href="/newSong" target="_blank">跳转</a> */}
                        {/* <button>点击</button> */}
                        {/* // <Link to="/newSong" >点击23</Link> */}
                    {/* // <BrowserRouter>
                    // <Switch>
                    
                    // <Link to="/newSong" target="_blank">链接</Link>
                    // <Route path="/news" component={SongList} />
                    // </Switch>
                    // </BrowserRouter> */}
                    {/* //     //控制音乐 */}
                        <div className='player-btn'>
                          <div className="player-list"><div className="musiclistPlay"></div></div>
                          <div className='player-item cut' onClick={this.playPrev.bind(this)}><div className='upcut'></div></div>
                          <div className='player-item control' onClick={this.playToggle.bind(this)}><div className={this.state.isPlay?'play':'pause'}></div></div>
                          <div className='player-item cut' onClick={this.playNext.bind(this)}><div className='downcut'></div></div>
                          {/* <div className="player-list"> */}
                              <WingBlank className="player-list">
                                <div onClick={this.showActionSheet} className="musicList">

                                    {/* {
                                        songlistlist.map(({name,ar})=>{
                                            return(
                                                <p>{name}</p>
                                            )
                                        })
                                    } */}
                                </div>
                                <WhiteSpace />
                                </WingBlank>
                                  {/* </div> */}
                                  {/* <button >点击</button> */}
                          {/* <div className="player-list"><div className="musiclistPlay"></div></div> */}
                        </div>
                        </div>    
            
                        )
                    

                    
                        // {/* <h2>歌曲播放</h2> */}
            })
        }
                
            </div>
        ) 
    }
}
export default Song